//
//  HistoryController.swift
//  LiteAccount
//
//  Created by 刘伟 on 2017/5/4.
//  Copyright © 2017年 刘伟. All rights reserved.
//

import UIKit

class HistoryController: UIViewController, BaseViewProtocal {
    
    let cellId = "cellId"
    
    var pageSize = 10
    var pageNum = 1
    var isLoaded = false
    var data = [AccountModel]() {
        didSet {
            table.reloadData()
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        self.setBaseViewConfig()
        self.view.backgroundColor = .white
        self.edgesForExtendedLayout = .init(rawValue: 0)
        self.view.addSubview(table)
        table.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        self.table.register(AccountCell.self, forCellReuseIdentifier: cellId)
        initMJHearder(target: table, selector: #selector(refreshData))
        initMJFooter(target: table, selector: #selector(loadMore))
    }
    
    override func viewWillAppear(_ animated: Bool) {
        if Defaults[.token] == nil {
            data = [AccountModel]()
            return
        }
        if !isLoaded {
            refreshData()
        }
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        MobClick.beginLogPageView("历史归档页")
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        MobClick.endLogPageView("历史归档页")
    }
    
    func refreshData() {
        pageNum = 1
        loadData()
    }
    
    func loadMore() {
        pageNum = pageNum + 1
        loadData()
    }
    
    func loadData() {
        var params = [String: Any]()
        params["token"] = Defaults[.token]
        params["pageNum"] = pageNum
        params["pageSize"] = pageSize
        APIClient.shared.fetchAccountList(params: params) { (response) in
            switch response {
            case let .success(accountList as [AccountModel], _):
                if self.pageNum == 1 {
                    self.data = accountList
                    self.table.mj_header.endRefreshing()
                } else {
                    for account in accountList {
                        self.data.append(account)
                    }
                }
                if accountList.count < self.pageSize {
                    self.table.mj_footer.endRefreshingWithNoMoreData()
                } else {
                    self.table.mj_footer.endRefreshing()
                }
            default:
                self.table.mj_header.endRefreshing()
                self.table.mj_footer.endRefreshingWithNoMoreData()
            }
        }

    }
    
    lazy var table: UITableView = { [unowned self] in
        let object = UITableView()
        object.backgroundColor = UIColor.la_bg
        // 指定数据源和代理
        object.dataSource = self
        object.delegate = self
        object.emptyDataSetSource = self
        object.emptyDataSetDelegate = self
        object.separatorStyle = .none
        object.estimatedRowHeight = 100
        object.rowHeight = UITableViewAutomaticDimension
        object.tableFooterView = UIView()
        return object
    }()

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

}

extension HistoryController: UITableViewDelegate, UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.data.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 100
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: cellId) as! AccountCell
        cell.data = self.data[indexPath.row]
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        debugPrint(indexPath.row)
        let nextView = AccountController()
        nextView.data = self.data[indexPath.row]
        nextView.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(nextView, animated: true)
    }
    
    func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
        var params = [String: Any]()
        params["token"] = Defaults[.token]
        params["accountId"] = self.data[indexPath.row].id
        debugPrint(params)
        let deleteAction = UITableViewRowAction(style: .default, title: "删除") { (action, indexPath) in
            print("删除", indexPath)
            let comfirmDialog = confirmDialog(title: "温馨提示", message: "你确定要删除吗", sure: {
                APIClient.shared.requestDeleteAccount(params: params, getResponse: { (response) in
                    switch response {
                    case let .success(_, message):
                        ProgressHUD.showSuccess(message)
                        self.data.remove(at: indexPath.row)
                    default: break
                    }
                })
            })
            self.present(comfirmDialog, animated: true, completion: nil)
        }
        return [deleteAction]
    }
    
}

extension HistoryController: DZNEmptyDataSetSource, DZNEmptyDataSetDelegate {
    
    func image(forEmptyDataSet scrollView: UIScrollView) -> UIImage? {
        let image = resizeImage(image: UIImage(named: "app_icon_light_blue.png")!, toSize: CGSize(width: 150, height: 150))
        return image
    }
    
    func buttonTitle(forEmptyDataSet scrollView: UIScrollView, for state: UIControlState) -> NSAttributedString? {
        if Defaults[.token] != nil {
            let text = "没有数据？点击尝试加载数据"
            let font = UIFont.la_Font(ofSize: 15)
            let attrStr = NSMutableAttributedString.init(string: text)
            attrStr.addAttributes([NSFontAttributeName : font], range: NSMakeRange(0, text.length))
            attrStr.addAttributes([NSForegroundColorAttributeName : UIColor.black], range: NSMakeRange(0, 4))
            attrStr.addAttributes([NSForegroundColorAttributeName : UIColor.la_app], range: NSMakeRange(5, 8))
            return attrStr
        }
        let text = "你还没有登录，点击登录"
        let font = UIFont.la_Font(ofSize: 15)
        let attrStr = NSMutableAttributedString.init(string: text)
        attrStr.addAttributes([NSFontAttributeName : font], range: NSMakeRange(0, 11))
        attrStr.addAttributes([NSForegroundColorAttributeName : UIColor.black], range: NSMakeRange(0, 6))
        attrStr.addAttributes([NSForegroundColorAttributeName : UIColor.la_app], range: NSMakeRange(7, 4))
        return attrStr
    }
    
    func backgroundColor(forEmptyDataSet scrollView: UIScrollView) -> UIColor? {
        return UIColor.white
    }
    
    func emptyDataSet(_ scrollView: UIScrollView, didTap button: UIButton) {
        debugPrint("你点击了登录按钮")
        if Defaults[.token] != nil {
            self.refreshData()
            return
        }
        if(checkLogin(target: self.tabBarController)){
            jumpHomeTab(target: self)
            self.isLoaded = false
            return
        }
        
    }
}

